import json
from datetime import datetime

from flask_wtf import FlaskForm
from wtforms import StringField, SelectField, TextAreaField, HiddenField, IntegerField
from wtforms.validators import Optional, DataRequired, NumberRange, ValidationError

from apps.forms.base_form import BaseForm
from models.biz_enum import Qualification


class QueryAlbumInfoForm(BaseForm):
    title = StringField('短剧标题', validators=[Optional()],
                        render_kw={"placeholder": "短剧标题", 'class': 'search-input'})
    release_year = SelectField('发行年份', validators=[Optional()],
                               render_kw={'class': 'filter-select'}, coerce=str, default='')
    album_status = SelectField('更新状态', validators=[Optional()],
                               render_kw={'class': 'filter-select'}, coerce=str, default='')

    def __init__(self, *args, **kwargs):
        super(QueryAlbumInfoForm, self).__init__(*args, **kwargs)
        self.release_year.choices = self.get_release_year_list(is_all=True)
        self.album_status.choices = self.get_album_status_list(is_all=True)


class CreateAlbumInfoForm(BaseForm):
    title = StringField('标题', validators=[DataRequired(message='请填写标题')],
                        render_kw={"placeholder": "请填写标题"})
    seq_num = StringField('总集数', validators=[DataRequired(message='请填写总集数')],
                          render_kw={"placeholder": "请填写总集数",
                                     "oninput": "this.value = this.value.replace(/[^0-9]/g, '');"})
    covers = HiddenField('封面图', validators=[DataRequired(message='请添加封面图')], default=[])
    release_year = SelectField('发行年份', coerce=str,
                               validators=[DataRequired(message='请选择发行年份')],
                               render_kw={"placeholder": "请填写发行年份"},
                               default=str(datetime.now().year))
    album_status = SelectField('更新状态', coerce=str,
                               validators=[DataRequired(message='请选择更新状态')])
    recommendation = StringField('推荐语(12汉字以内)', validators=[Optional()],
                                 render_kw={"placeholder": "请填写推荐语", "maxlength": 12})
    introduction = TextAreaField('简介(200汉字以内)', validators=[Optional()],
                                 render_kw={"placeholder": "请填写推荐语", "maxlength": 200, "style": "height: 100px;"})
    tags = HiddenField('标签(1-3个)', validators=[DataRequired(message='请添加标签')], default=[])
    qualification = SelectField('资质状态', coerce=str,
                                validators=[DataRequired(message='请选择资质状态')],
                                render_kw={"record_key": Qualification.APPROVED.value,
                                           "onchange": "changeQualification();"})

    license_num = StringField('许可证号', validators=[Optional()], render_kw={"placeholder": "请填写许可证号"})
    registration_num = StringField('登记号', validators=[Optional()], render_kw={"placeholder": "请填写登记号"})
    ordinary_record_num = StringField('普通备案号', validators=[Optional()],
                                      render_kw={"placeholder": "请填写普通备案号"})
    key_record_num = StringField('重点备案号', validators=[Optional()], render_kw={"placeholder": "请填写重点备案号"})

    record_type = SelectField('备案号类型', coerce=str,
                              validators=[DataRequired(message='请选择备案号类型')])
    broadcast_record_number = StringField('广电备案号', validators=[DataRequired(message='请填写广电备案号')],
                                          render_kw={"placeholder": "请填写广电备案号"})

    name = StringField('剧名', validators=[DataRequired(message='请填写剧名')], render_kw={"placeholder": "请填写剧名"})
    duration = StringField('平均单集时长，单位分钟', validators=[DataRequired(message='请填写平均单集时长')],
                           render_kw={"placeholder": "请填写平均单集时长",
                                      "oninput": "this.value = this.value.replace(/[^0-9]/g, '');"})
    seqs_count = StringField('集数', validators=[DataRequired(message='请填写集数')],
                             render_kw={"placeholder": "请填写集数",
                                        "oninput": "this.value = this.value.replace(/[^0-9]/g, '');"})
    production_organisation = StringField('制作机构', validators=[DataRequired(message='请填写制作机构')],
                                          render_kw={"placeholder": "请填写制作机构"})
    director = StringField('导演(多个以英文逗号分隔)', validators=[DataRequired(message='请填写导演')],
                           render_kw={"placeholder": "请填写导演"})
    producer = StringField('制作人(多个以英文逗号分隔)', validators=[DataRequired(message='请填写制作人')],
                           render_kw={"placeholder": "请填写制作人"})
    actor = StringField('演员(多个以英文逗号分隔)', validators=[DataRequired(message='请填写演员')],
                        render_kw={"placeholder": "请填写演员"})
    summary = TextAreaField('内容梗概(1000 汉字以内)', validators=[Optional()],
                            render_kw={"placeholder": "请填写内容梗概", "maxlength": 1000, "style": "height: 100px;"})
    cost_distribution_uri = HiddenField('成本配置比例情况', validators=[DataRequired(message='请添加成本配置比例情况')],
                                        default="")
    assurance_uri = HiddenField('承诺书', validators=[Optional()], default="")
    playlet_production_cost = SelectField('制作成本类型', coerce=str,
                                          validators=[DataRequired(message='请选择制作成本类型')])
    screen_writer = StringField('编剧(多个以英文逗号分隔)', validators=[Optional()],
                                render_kw={"placeholder": "请填写编剧"})

    def __init__(self, *args, **kwargs):
        super(CreateAlbumInfoForm, self).__init__(*args, **kwargs)
        self.release_year.choices = self.get_release_year_list()
        self.album_status.choices = self.get_album_status_list()
        self.qualification.choices = self.get_qualification_list()
        self.record_type.choices = self.get_record_type_list()
        self.playlet_production_cost.choices = self.get_playlet_production_cost_list()

    def validate_seq_num(self, field):
        if not self.is_integer(field.data):
            raise ValidationError('必须是一个大于0的整数')

    def validate_duration(self, field):
        if not self.is_integer(field.data):
            raise ValidationError('必须是一个大于0的整数')

    def validate_seqs_count(self, field):
        if not self.is_integer(field.data):
            raise ValidationError('必须是一个大于0的整数')

    def validate_covers(self, field):
        try:
            covers_data = json.loads(field.data)
            if len(covers_data) < 1:
                raise ValidationError('请添加封面图')
        except Exception as e:
            raise ValidationError('请添加封面图')

    def validate_tags(self, field):
        try:
            tags_data = json.loads(field.data)
            if len(tags_data) < 1:
                raise ValidationError('请添加标签')
        except Exception as e:
            raise ValidationError('请添加标签')

    def validate_cost_distribution_uri(self, field):
        try:
            json_data = json.loads(field.data)
            if not json_data:
                raise ValidationError('请添加成本配置比例情况')
        except Exception as e:
            raise ValidationError('请添加成本配置比例情况')


class GetAlbumInfoForm(BaseForm):
    title = StringField('标题', render_kw={'readonly': True})
    seq_num = StringField('总集数', render_kw={'readonly': True})
    covers = HiddenField('封面图')
    release_year = StringField('发行年份', render_kw={'readonly': True})
    album_status = StringField('更新状态', render_kw={'readonly': True})
    recommendation = StringField('推荐语(12汉字以内)', render_kw={'readonly': True})
    introduction = TextAreaField('简介(200汉字以内)', render_kw={'readonly': True})
    tags = HiddenField('标签(1-3个)')
    qualification = StringField('资质状态', render_kw={'readonly': True})

    license_num = StringField('许可证号', render_kw={'readonly': True})
    registration_num = StringField('登记号', render_kw={'readonly': True})
    ordinary_record_num = StringField('普通备案号', render_kw={'readonly': True})
    key_record_num = StringField('重点备案号', render_kw={'readonly': True})

    record_type = StringField('备案号类型', render_kw={'readonly': True})
    broadcast_record_number = StringField('广电备案号', render_kw={'readonly': True})

    name = StringField('剧名', render_kw={'readonly': True})
    duration = StringField('平均单集时长，单位分钟', render_kw={'readonly': True})
    seqs_count = StringField('集数', render_kw={'readonly': True})
    production_organisation = StringField('制作机构', render_kw={'readonly': True})
    director = StringField('导演', render_kw={'readonly': True})
    producer = StringField('制作人', render_kw={'readonly': True})
    actor = StringField('演员', render_kw={'readonly': True})
    summary = TextAreaField('内容梗概(1000 汉字以内)', render_kw={'readonly': True})
    cost_distribution_uri = HiddenField('成本配置比例情况')
    assurance_uri = HiddenField('承诺书')
    playlet_production_cost = StringField('制作成本类型', render_kw={'readonly': True})
    screen_writer = StringField('编剧', render_kw={'readonly': True})

    def __init__(self, model_dict=None, *args, **kwargs):
        super(GetAlbumInfoForm, self).__init__(*args, **kwargs)
        if model_dict:
            self.title.data = model_dict.get('title')
            self.seq_num.data = model_dict.get('seq_num')
            self.covers.data = model_dict.get('covers')
            self.release_year.data = model_dict.get('release_year')
            self.album_status.data = model_dict.get('album_status_name')
            self.recommendation.data = model_dict.get('recommendation')
            self.introduction.data = model_dict.get('introduction')
            self.tags.data = model_dict.get('tags')
            self.qualification.data = model_dict.get('qualification_name')

            self.license_num.data = model_dict.get('record_info').get('license_num')
            self.registration_num.data = model_dict.get('record_info').get('registration_num')
            self.ordinary_record_num.data = model_dict.get('record_info').get('ordinary_record_num')
            self.key_record_num.data = model_dict.get('record_info').get('key_record_num')

            self.record_type.data = model_dict.get('broadcast_record_info').get('record_type_name')
            self.broadcast_record_number.data = model_dict.get('broadcast_record_info').get('broadcast_record_number')

            self.name.data = model_dict.get('record_material').get('name')
            self.duration.data = model_dict.get('record_material').get('duration')
            self.seqs_count.data = model_dict.get('record_material').get('seqs_count')
            self.production_organisation.data = model_dict.get('record_material').get('production_organisation')
            self.director.data = ','.join(model_dict.get('record_material').get('director'))
            self.producer.data = ','.join(model_dict.get('record_material').get('producer'))
            self.actor.data = ','.join(model_dict.get('record_material').get('actor'))
            self.summary.data = model_dict.get('record_material').get('summary')
            self.cost_distribution_uri.data = model_dict.get('record_material').get('cost_distribution_uri')
            self.assurance_uri.data = model_dict.get('record_material').get('assurance_uri')
            self.playlet_production_cost.data = model_dict.get('record_material').get('playlet_production_cost_name')
            self.screen_writer.data = ','.join(model_dict.get('record_material').get('screen_writer'))


class UpdateAlbumInfoForm(BaseForm):
    album_info_id = HiddenField('')
    title = StringField('标题', validators=[DataRequired(message='请填写标题')],
                        render_kw={"placeholder": "请填写标题"})
    seq_num = StringField('总集数', validators=[DataRequired(message='请填写总集数')],
                          render_kw={"placeholder": "请填写总集数",
                                     "oninput": "this.value = this.value.replace(/[^0-9]/g, '');"})
    covers = HiddenField('封面图', validators=[DataRequired(message='请添加封面图')], default=[])
    release_year = SelectField('发行年份', coerce=str,
                               validators=[DataRequired(message='请选择发行年份')],
                               render_kw={"placeholder": "请填写发行年份"},
                               default=str(datetime.now().year))
    album_status = SelectField('更新状态', coerce=str,
                               validators=[DataRequired(message='请选择更新状态')])
    recommendation = StringField('推荐语(12汉字以内)', validators=[Optional()],
                                 render_kw={"placeholder": "请填写推荐语", "maxlength": 12})
    introduction = TextAreaField('简介(200汉字以内)', validators=[Optional()],
                                 render_kw={"placeholder": "请填写推荐语", "maxlength": 200, "style": "height: 100px;"})
    tags = HiddenField('标签(1-3个)', validators=[DataRequired(message='请添加标签')], default=[])
    qualification = SelectField('资质状态', coerce=str,
                                validators=[DataRequired(message='请选择资质状态')],
                                render_kw={"record_key": Qualification.APPROVED.value,
                                           "onchange": "changeQualification();"})

    license_num = StringField('许可证号', validators=[Optional()], render_kw={"placeholder": "请填写许可证号"})
    registration_num = StringField('登记号', validators=[Optional()], render_kw={"placeholder": "请填写登记号"})
    ordinary_record_num = StringField('普通备案号', validators=[Optional()],
                                      render_kw={"placeholder": "请填写普通备案号"})
    key_record_num = StringField('重点备案号', validators=[Optional()], render_kw={"placeholder": "请填写重点备案号"})

    record_type = SelectField('备案号类型', coerce=str,
                              validators=[DataRequired(message='请选择备案号类型')])
    broadcast_record_number = StringField('广电备案号', validators=[DataRequired(message='请填写广电备案号')],
                                          render_kw={"placeholder": "请填写广电备案号"})

    name = StringField('剧名', validators=[DataRequired(message='请填写剧名')], render_kw={"placeholder": "请填写剧名"})
    duration = StringField('平均单集时长，单位分钟', validators=[DataRequired(message='请填写平均单集时长')],
                           render_kw={"placeholder": "请填写平均单集时长",
                                      "oninput": "this.value = this.value.replace(/[^0-9]/g, '');"})
    seqs_count = StringField('集数', validators=[DataRequired(message='请填写集数')],
                             render_kw={"placeholder": "请填写集数",
                                        "oninput": "this.value = this.value.replace(/[^0-9]/g, '');"})
    production_organisation = StringField('制作机构', validators=[DataRequired(message='请填写制作机构')],
                                          render_kw={"placeholder": "请填写制作机构"})
    director = StringField('导演(多个以英文逗号分隔)', validators=[DataRequired(message='请填写导演')],
                           render_kw={"placeholder": "请填写导演"})
    producer = StringField('制作人(多个以英文逗号分隔)', validators=[DataRequired(message='请填写制作人')],
                           render_kw={"placeholder": "请填写制作人"})
    actor = StringField('演员(多个以英文逗号分隔)', validators=[DataRequired(message='请填写演员')],
                        render_kw={"placeholder": "请填写演员"})
    summary = TextAreaField('内容梗概(1000 汉字以内)', validators=[Optional()],
                            render_kw={"placeholder": "请填写内容梗概", "maxlength": 1000, "style": "height: 100px;"})
    cost_distribution_uri = HiddenField('成本配置比例情况', validators=[DataRequired(message='请添加成本配置比例情况')],
                                        default="")
    assurance_uri = HiddenField('承诺书', validators=[Optional()], default="")
    playlet_production_cost = SelectField('制作成本类型', coerce=str,
                                          validators=[DataRequired(message='请选择制作成本类型')])
    screen_writer = StringField('编剧(多个以英文逗号分隔)', validators=[Optional()],
                                render_kw={"placeholder": "请填写编剧"})

    def __init__(self, model_dict=None, *args, **kwargs):
        super(UpdateAlbumInfoForm, self).__init__(*args, **kwargs)
        self.release_year.choices = self.get_release_year_list()
        self.album_status.choices = self.get_album_status_list()
        self.qualification.choices = self.get_qualification_list()
        self.record_type.choices = self.get_record_type_list()
        self.playlet_production_cost.choices = self.get_playlet_production_cost_list()

        if model_dict:
            self.album_info_id.data = model_dict.get('id')
            self.title.data = model_dict.get('title')
            self.seq_num.data = model_dict.get('seq_num')
            self.covers.data = model_dict.get('covers')
            self.release_year.data = str(model_dict.get('release_year'))
            self.album_status.data = model_dict.get('album_status')
            self.recommendation.data = model_dict.get('recommendation')
            self.introduction.data = model_dict.get('introduction')
            self.tags.data = model_dict.get('tags')
            self.qualification.data = model_dict.get('qualification')

            self.license_num.data = model_dict.get('record_info').get('license_num')
            self.registration_num.data = model_dict.get('record_info').get('registration_num')
            self.ordinary_record_num.data = model_dict.get('record_info').get('ordinary_record_num')
            self.key_record_num.data = model_dict.get('record_info').get('key_record_num')

            self.record_type.data = model_dict.get('broadcast_record_info').get('record_type')
            self.broadcast_record_number.data = model_dict.get('broadcast_record_info').get('broadcast_record_number')

            self.name.data = model_dict.get('record_material').get('name')
            self.duration.data = model_dict.get('record_material').get('duration')
            self.seqs_count.data = model_dict.get('record_material').get('seqs_count')
            self.production_organisation.data = model_dict.get('record_material').get('production_organisation')
            self.director.data = ','.join(model_dict.get('record_material').get('director'))
            self.producer.data = ','.join(model_dict.get('record_material').get('producer'))
            self.actor.data = ','.join(model_dict.get('record_material').get('actor'))
            self.summary.data = model_dict.get('record_material').get('summary')
            self.cost_distribution_uri.data = model_dict.get('record_material').get('cost_distribution_uri')
            self.assurance_uri.data = model_dict.get('record_material').get('assurance_uri')
            self.playlet_production_cost.data = model_dict.get('record_material').get('playlet_production_cost')
            self.screen_writer.data = ','.join(model_dict.get('record_material').get('screen_writer'))

    def is_integer(self, value_data):
        try:
            if value_data:
                i_value_data = int(value_data)
                if i_value_data > 0:
                    return True

            return False
        except Exception as e:
            return False

    def validate_seq_num(self, field):
        if not self.is_integer(field.data):
            raise ValidationError('必须是一个大于0的整数')

    def validate_duration(self, field):
        if not self.is_integer(field.data):
            raise ValidationError('必须是一个大于0的整数')

    def validate_seqs_count(self, field):
        if not self.is_integer(field.data):
            raise ValidationError('必须是一个大于0的整数')

    def validate_covers(self, field):
        try:
            covers_data = json.loads(field.data)
            if len(covers_data) < 1:
                raise ValidationError('请添加封面图')
        except Exception as e:
            raise ValidationError('请添加封面图')

    def validate_tags(self, field):
        try:
            tags_data = json.loads(field.data)
            if len(tags_data) < 1:
                raise ValidationError('请添加标签')
        except Exception as e:
            raise ValidationError('请添加标签')

    def validate_cost_distribution_uri(self, field):
        try:
            json_data = json.loads(field.data)
            if not json_data:
                raise ValidationError('请添加成本配置比例情况')
        except Exception as e:
            raise ValidationError('请添加成本配置比例情况')
